import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:yuan_hang_app/base/base_state.dart';
import 'package:yuan_hang_app/base/full_base_page.dart';
import 'package:yuan_hang_app/utils/router_helper.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/views/home/view/order/model/sales_order.dart';
import 'package:yuan_hang_app/views/home/view/order/sales_order_detail_page.dart';

import '../../../../http/api.dart';
import '../../../../http/http_utils.dart';
import '../../../../res/w_colors.dart';
import '../../../../res/w_dimens.dart';
import '../../../../utils/common_req_utils.dart';
import '../../../../utils/common_utils.dart';
import '../../../../widget/custom_search.dart';
import '../../../../widget/sort_content.dart';
import '../../../../widget/status_btn.dart';
import '../../../../widget/w_line.dart';
import '../../../../widget/w_list_view.dart';
import '../../../../widget/w_popup_window.dart';
import '../../../../widget/w_text.dart';

class SalesOrderListPage extends StatefulWidget {
  const SalesOrderListPage({super.key});

  @override
  BaseState<SalesOrderListPage> createState() => SalesOrderListPageState();
}

class SalesOrderListPageState extends BaseState<SalesOrderListPage> {

  Map<String, dynamic> queryParams = {
    "pageNum": 1,
    "limit": 20,
  };
  Map sortParams = {};
  WListViewState? listState;
  List<SalesOrder> dataList = [];

  @override
  void initState() {
    super.initState();
    fetchDataList();
  }

  void fetchDataList() {
    HttpUtils().get(Api.getSalesOrderList, queryParams: queryParams).then((value) {
      hideLoading();
      if (value.resultCode == 200) {
        if (value.data != null) {
          List data = value.data["records"] ?? [];
          List<SalesOrder> list = data.map((item) => SalesOrder.fromJson(item)).toList();
          listState?.onRefreshData(list, queryParams["pageNum"]);
          if (queryParams["pageNum"] == 1) {
            dataList.clear();
          }
          dataList.addAll(list);
        }
      } else {
        listState?.onFail(value.errMsg);
      }
    }).catchError((e){
      hideLoading();
      listState?.onFail(e);
    });
  }


  @override
  FullBasePage buildState(BuildContext context) {
    return FullBasePage(
      title: "销售订单列表",
      child: Column(
        children: [
          CustomSearch(
            hintText: "客户名称/手机号",
            onSortClick: () {
              WPopupWindow.showSort(
                  context: context,
                  sortType: SortType.SALES_ORDER,
                  sortParams: sortParams,
                  onSelected: (Map params) {
                    sortParams = params;
                    params.forEach((key, value) {
                      queryParams[key] = value;
                      if (queryParams.containsKey(key) && value == null) {
                        queryParams.remove(key);
                      }
                    });
                    //   print(params);
                    showLoading();
                    fetchDataList();
                  });
            },
            onTextChange: (text) {
              queryParams["pageNum"] = 1;
              queryParams["queryParam"] = text;
              CommonUtils.antiShake(fetchDataList);
            },
          ),
          Expanded(
              child: WListView(
                padding: EdgeInsets.only(top: 10.px),
                itemBuilder: _listItem,
                getDataList: (currentState, page) {
                  listState = currentState;
                  queryParams["pageNum"] = page;
                  fetchDataList();
                },
              )),
        ],
      ),
    );
  }

  Widget _listItem(context, index, dataList) {
    SalesOrder item = dataList[index];

    return GestureDetector(
      onTap: () => {
        RouteHelper.pushWidget(context,  SalesOrderDetailPage(orderCode: item.orderCode,)).then((_) {
          queryParams["pageNum"] = 1;
          fetchDataList();
        })
      },
      child: Container(
        decoration: BoxDecoration(boxShadow: [
          BoxShadow(
              color: WColors.CDFEFFB,
              offset: const Offset(0, 1),
              blurRadius: 3.px)
        ], borderRadius: BorderRadius.circular(10.px), color: Colors.white),
        margin: EdgeInsets.only(left: 10.px, right: 10.px, bottom: 10.px),
        padding: EdgeInsets.only(right: 10.px, bottom: 10.px),
        child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              SizedBox(height: 5.px),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  WLine(
                    height: 16.px,
                    width: 4.px,
                    color: WColors.primaryColor,
                  ),
                  SizedBox(width: 5.px,),
                  Expanded(
                    child: WText(
                      item.orderCode ?? "",
                      style: TextStyle(
                          fontSize: WDimens.tsLarge,
                          color: WColors.mainTextColor,
                          fontWeight: FontWeight.bold),
                    ),
                  ),
                  StatusBtn(
                    isItemBtn: true,
                    height: 24.px,
                    text: CommonReqUtils.exchangeCodeToName(
                        CommonReqUtils.storeCarStatus, item.status),
                    color: WColors.primaryColor,
                    //   color: tagStyle["color"],
                  )
                ],
              ),
              WLine(
                height: 1.px,
                marginTop: 6.px,
                marginBottom: 6.px,
              ),
              Padding(
                padding: EdgeInsets.only(left: 10.px),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    WText(
                      "${item.modelName} · ${item.versionName} · ${item.outColor} · ${item.inColor}",
                      style: TextStyle(
                          fontSize: WDimens.tsMedium,
                          color: WColors.mainTextColor),
                    ),
                    SizedBox(
                      height: 5.px,
                    ),
                    WText(
                      "${item.custName} · ${item.phone}",
                      style: TextStyle(
                          fontSize: WDimens.tsMedium,
                          color: WColors.mainTextColor),
                    ),
                    SizedBox(
                      height: 5.px,
                    ),
                    WText(
                       "交付中心: ${item.centerShopName}",
                      style: TextStyle(
                          fontSize: WDimens.tsMedium,
                          color: WColors.mainTextColor),
                    ),
                    SizedBox(
                      height: 5.px,
                    ),
                    WText(
                      "提车日期: ${item.deliveryDate}",
                      style: TextStyle(
                          fontSize: WDimens.tsMedium,
                          color: WColors.mainTextColor),
                    ),
                  ],
                ),
              ),
            ]),
      ),
    );
  }

}